宣告
宣告protocol
@required
是指採用這個protocol的類別一定要實現這個方法
且預設是指@required
@optional
是指採用這個protocol的類別可以選擇性實現這個方法
英文字屬於哪個修飾子
- @required: a b c d g h
- @optional: e f
Template.h1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| @class Template; @protocol TemplateDelegate<NSObject>
@required -(void)TemplateView:(Template*)templateView WithValueChangeRequired:(float)value;
@optional -(void)TemplateView:(Template*)templateView WithValueChangeOptional:(float)value;
@required
@end
|
宣告delegate
宣告這個類別有一個delegate且採用了TemplateDelegate
這個protocol
Template.h1 2 3
| @interface Template : UIView @property (weak)id <TemplateDelegate>delegate; @end
|
實作
Template.m1 2 3 4 5 6
| [_delegate TemplateView:self WithValueChangeRequired:1.0f];
if ([_delegate respondsToSelector:@selector(TemplateView:WithValueChangeOptional:)]) { [_delegate TemplateView:self WithValueChangeOptional:1.0f]; }
|
套用
Usage.m1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| @interface Usage ()<TemplateDelegate> { Template *template; } @end
@implementation Usage
- (void)viewDidLoad { template.delegate = self; }
-(void)TemplateView:(Template*)templateView WithValueChangeRequired:(float)value{ }
@end
|